import {
    CompleteState,
    AnswerState,
    Cardinality,
    BaseType
} from './ServiceConst'

import QtiAdapter from './QtiAdapter'

import CardinalityChecker from './CardinalityChecker'

import ServiceUtils from './ServiceUtils'




//返回作答项结果模型
var State = {
    getNormalItemResult: function (item, correctAnswer, userItemAnswer) {
        let correctAnswerVal = (correctAnswer && correctAnswer.value) || [],
            userAnswerVal = userItemAnswer.value || [];

        let itemResult = {
            id: item.id,
            unAnsweredCount: 0, //未作答空
            answerState: false,
            completeState: CompleteState.ALL_ANSWERED,
            candidateResponse: ServiceUtils.deepClone(userAnswerVal), //用户答案
            correctResponse: ServiceUtils.deepClone(correctAnswerVal) //正确答案
        };

        //未作答数，排除空字符串
        let answeredCount = userAnswerVal.filter(val => {
            return val !== '';
        }).length;

        //未完成数
        if (correctAnswerVal.length !== 0) {
            itemResult.unAnsweredCount = correctAnswerVal.length - answeredCount
        }

        //完成状态
        if (answeredCount === 0) {
            itemResult.completeState = CompleteState.UNANSWERED;
        } else if (answeredCount < correctAnswerVal.length) {
            itemResult.completeState = CompleteState.PARTICAL_ANSWERED;
        }

        //正误状态
        if (userItemAnswer.answerState === true || userItemAnswer.answerState === false) {
            //自带结果，直接使用用户作答结果
            itemResult.answerState = userItemAnswer.answerState;
        } else if ((!correctAnswer || !correctAnswer.value || !correctAnswerVal.length) && item.getModel) {
            //小题还未加载
            itemResult.answerState = false;
        } else if (item.subjective) {
            //主观题默认正确
            itemResult.answerState = true;
        } else {
            //判断用户作答情况
            itemResult.answerState = CardinalityChecker.checkAnswer(correctAnswer, userAnswerVal);
        }
        return itemResult;
    },
    getQtiItemResult: function (qtiState) {
        // let itemId = Object.keys(qtiState)[0];
        let answerState = QtiAdapter.parseAnswerState(qtiState);
        let ids = Object.keys(answerState.items);
        let itemResult = answerState.items[ids[0]];
        return itemResult;
    },
    getItemState: function (item, userAnswer) {
        let correctAnswer = item.correctAnswer || {},
            correctAnswerVal = (correctAnswer && correctAnswer.value) || [],
            userItemAnswer = userAnswer.value || [],
            itemResult;

        if (QtiAdapter.isQtiAnswerState(userAnswer)) {
            //复合类习题内不会嵌套Qti的复合题，直接单做单题处理即可
            itemResult = this.getQtiItemResult(userAnswer);
        } else {
            itemResult = this.getNormalItemResult(item, correctAnswer, userAnswer)
        }
        itemResult.id = item.id;

        return itemResult;
    },
    isQtiState: function (userAnswer) {
        let allQti = true;
        for (var id in userAnswer) {
            if (userAnswer.hasOwnProperty(id)) {
                allQti = QtiAdapter.isQtiAnswerState(userAnswer[id]);
                if (!allQti) {
                    break;
                }
            }
        }
        return allQti;
    },
    getAnswerState: function (model, userAnswer) {

        let that = this,
            items = model.items || [],
            itemsCount = items.length || 1,
            result = {
                answerState: true, //正确错误
                items: {}
            };

        let ids = Object.keys(userAnswer);
        //qti复合题，只有一个Qti题型时（一个Qti实例加载出来的习题，包含Qti的复合、填空、选做）
        if (items.length > 0 && ids.length === 1 && this.isQtiState(userAnswer)) {
            return QtiAdapter.parseAnswerState(userAnswer[ids[0]]);
        }

        if (items.length === 0) {
            if (!userAnswer[model.id]) {
                throw new Error('答案id和模型id不匹配', userAnswer, model.id);
            }
            //单题
            result.items[model.id] = that.getItemState(model, userAnswer[model.id] || {});
        } else {
            //普通复合题
            items.forEach(item => {
                let id = item.id;
                if (!userAnswer[item.id]) {
                    throw new Error('答案id和模型id不匹配', userAnswer, id);
                }
                result.items[id] = that.getItemState(item, userAnswer[id] || {});
            });
        }




        let resultItem;

        for (var id in result.items) {
            if (!result.items.hasOwnProperty(id)) {
                continue;
            }
            resultItem = result.items[id];

            //只要有一小题错误，就认为整道题错误
            if (resultItem.answerState === false) {
                result.answerState = false;
            }
        }


        return result;
    },
    getDefaultState(model) {
        let answerState = {
            answerState: false,
            items: {}
        };

        // let model = this.getQuestionModel();
        if (model.items && model.items.length > 0) {
            model.items.forEach(function (item) {
                answerState.items[item.id] = {
                    id: item.id,
                    unAnsweredCount: 0, //未作答空
                    answerState: false,
                    completeState: CompleteState.UNANSWERED,
                    candidateResponse: [], //用户答案
                    correctResponse: ServiceUtils.deepClone(item.correctAnswer) //正确答案
                }
            }, this);
        } else {
            answerState.items[model.id] = {
                id: model.id,
                unAnsweredCount: 0, //未作答空
                answerState: false,
                completeState: CompleteState.UNANSWERED,
                candidateResponse: [], //用户答案
                correctResponse: [] //正确答案
            }
        }
        return answerState;
    }
}



var AnswerStateChecker = {
    /**
     * 获取作答结果模型
     * 
     * @param {any} model 标准模型
     * @param {any} userAnswer 用户答案  
     * @returns 返回值 {
                answerState: true, //正确错误
                completeState: CompleteState.UNANSWERED, //是否作答
                unAnsweredCount: 0, //
                items: {}
            }
     */
    getCheckState(model, userAnswer) {
        return State.getAnswerState(model, userAnswer);
    },
    /**
     * 
     * 获取默认情况下的作答结果模型
     * 
     * @param {any} model 
     * @returns 
     */
    getDefaultState(model) {
        return State.getDefaultState(model);
    }
}

export default AnswerStateChecker